package com.leyou.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {

    @Autowired
    private FastFileStorageClient storageClient;

    private static final Logger logger= LoggerFactory.getLogger(UploadService.class);
  //支持的文件类型
    private static final List<String> suffixes= Arrays.asList("image/png", "image/jpeg");
    //判断图片类型和内容是否正确
    public String upload(MultipartFile file) {
        try {
            //校验图片类型
            String type=file.getContentType();
            if (!suffixes.contains(type)){
                logger.info("上传失败，文件类型不匹配：{}",type);
                return null;
            }
            //校验图片内容
            BufferedImage image= ImageIO.read(file.getInputStream());
            if (image==null){
                logger.info("上传失败，文件内容不符合要求");
                return null;
            }
          /*  //保存图片，生成保存目录
            File dir=new File("D:/test/upload");
            if (!dir.exists()){
                dir.mkdirs();
            }
            //保存图片
            file.transferTo(new File(dir,file.getOriginalFilename()));*/

            // 2、将图片上传到FastDFS
            // 2.1、获取文件后缀名
            String extension = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(),
                    file.getSize(), extension, null);

            //拼接图片地址
            String url="http://image.leyou.com/"+storePath.getFullPath();
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }


    }
}
